package org.esk.dablog.service.spi;

import org.esk.dablog.service.PictureManager;
import org.esk.dablog.service.EntryManager;
import org.esk.dablog.model.Picture;
import org.esk.dablog.exceptions.BusinessException;
import org.esk.dablog.dao.PictureDAO;

/**
 * This class implements Picture Manager interface
 * User: jc
 * Date: 30.11.2006
 * Time: 12:50:53
 * $Id:$
 */
public class PictureManagerImpl implements PictureManager {
    /**
     * picture DAO is used to load and update Picture instances
     */
    private PictureDAO pictureDAO;

    /**
     * Picture instances are being saved or deleted by its parent Entry entity
     */
    private EntryManager entryManager;


    public void setEntryManager(EntryManager entryManager) {
        this.entryManager = entryManager;
    }

    public void setPictureDAO(PictureDAO pictureDAO) {
        this.pictureDAO = pictureDAO;
    }

    /**
     * returns Picture by its id
     * @param id
     * @return
     * @throws BusinessException
     */
    public Picture getPicture(long id) throws BusinessException {
        Picture p = pictureDAO.getPicture(id);
        if(p == null) {
            throw new BusinessException("Picture with id " + id + " not found");
        }
        return p;
    }

    /**
     * saves picture
     * @param picture
     * @throws BusinessException
     */
    public void savePicture(Picture picture) throws BusinessException {
        if(picture.getEntry() == null){
            throw new BusinessException("Cannot save orphaned Picture: pic.entry is null");                   
        }
        entryManager.updateEntry(picture.getEntry());
    }

    /**
     * deletes picture
     * @param picture
     */
    public void deletePicture(Picture picture) throws BusinessException {
        Picture pic = getPicture(picture.getId());
        //TODO add security check - this is the reason to load pic from database
        pictureDAO.deletePicture(pic.getId());
    }


}
